/*            Copyright(c) 2006-2008 Dave Sexton           *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace DaveSexton.DocProject
{
	public static class ComponentDescriptor
	{
		#region Private / Protected
		private static readonly Dictionary<Type, Data> typeData = new Dictionary<Type, Data>();
		#endregion

		#region Methods
		private static Data GetTypeData(Type type)
		{
			if (type == null)
				throw new ArgumentNullException("type");

			Data data;

			if (typeData.ContainsKey(type))
				data = typeData[type];
			else
				data = new Data();

			return data;
		}

		[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
		public static string GetDisplayName(Type type)
		{
			Data data = GetTypeData(type);

			if (data.displayName == null)
			{
				AttributeCollection collection = TypeDescriptor.GetAttributes(type);
				DisplayNameAttribute attribute = (DisplayNameAttribute) collection[typeof(DisplayNameAttribute)];

				if (attribute == null || attribute.IsDefaultAttribute())
					data.displayName = type.Name;
				else
					data.displayName = attribute.DisplayName ?? type.Name;

				typeData[type] = data;
			}

			return data.displayName;
		}

		[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
		public static string GetDescription(Type type)
		{
			Data data = GetTypeData(type);

			if (data.description == null)
			{
				AttributeCollection collection = TypeDescriptor.GetAttributes(type);
				DescriptionAttribute attribute = (DescriptionAttribute) collection[typeof(DescriptionAttribute)];

				if (attribute == null || attribute.IsDefaultAttribute())
					data.description = string.Empty;
				else
					data.description = attribute.Description ?? string.Empty;

				typeData[type] = data;
			}

			return data.description;
		}
		#endregion

		#region Nested
		private struct Data
		{
			public string displayName, description;
		}
		#endregion
	}
}
